//
//  AudioRecorderViewController.m
//  AVFoundation
//
//  Created by bao on 2018/6/22.
//  Copyright © 2018年 bao. All rights reserved.
//

#import "AudioRecorderViewController.h"

#import <AVFoundation/AVFoundation.h>

@interface AudioRecorderViewController () <AVAudioRecorderDelegate, AVAudioPlayerDelegate>

@property (weak, nonatomic) IBOutlet UIButton *recorderButton;
@property (weak, nonatomic) IBOutlet UILabel *label;

@property (nonatomic, strong) AVAudioRecorder *audioRecorder;

@property (nonatomic, strong) AVAudioPlayer *audioPlayer;

@end

@implementation AudioRecorderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    NSString *tmpDir = NSTemporaryDirectory();
    NSString *filePath = [tmpDir stringByAppendingPathComponent:@"memo.caf"];
    NSURL *fileUrl = [NSURL fileURLWithPath:filePath];
    DCLog(@"%@", filePath);
    self.label.text = [NSString stringWithFormat:@"录音临时存放位置：%@", filePath];
    NSDictionary *settings = @{
                               AVFormatIDKey : @(kAudioFormatMPEG4AAC), // 音频格式
                               AVSampleRateKey : @44100.0f, // 采样率
                               AVNumberOfChannelsKey : @1,  // 通道数
                               };
    NSError *error = nil;
    AVAudioRecorder *audioRecorder = [[AVAudioRecorder alloc] initWithURL:fileUrl settings:settings error:&error];
    if (error) {
        DCLog(@"error : %@", error);
    } else {
        audioRecorder.delegate = self;
        [audioRecorder prepareToRecord];
        self.audioRecorder = audioRecorder;
    }
    
}

- (void)playRecorder
{
    self.recorderButton.enabled = NO;
    self.navigationItem.rightBarButtonItem.enabled = NO;
    
    NSString *filename = @"recorder.m4a";
    NSString *docsDir = [self documentsDirectory];
    NSString *destPath = [docsDir stringByAppendingPathComponent:filename];
    NSURL *fileUrl = [NSURL fileURLWithPath:destPath];
    
    NSError *error = nil;
    self.audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileUrl error:&error];
    self.audioPlayer.delegate = self;
    if (error) {
        self.recorderButton.enabled = NO;
        self.navigationItem.rightBarButtonItem.enabled = NO;
        DCLog(@"error : %@", error.localizedDescription);
    } else {
        [self.audioPlayer prepareToPlay];
        [self.audioPlayer play];
        self.navigationItem.title = @"播放中...";
    }
}

- (IBAction)record {
    
    self.recorderButton.enabled = NO;
    self.navigationItem.rightBarButtonItem.enabled = NO;
    
    self.navigationItem.title = @"录制中...";
    
    [self.audioRecorder record];
    
    __weak typeof(self) weakSelf = self;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (!weakSelf) return;
        
        [weakSelf.audioRecorder stop];
        
    });
    
}

- (NSString *)documentsDirectory {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return [paths objectAtIndex:0];
}

#pragma mark - AVAudioRecorderDelegate

- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag
{
    DCLog(@"录制完成 : %d", flag);
    self.navigationItem.title = nil;
    self.recorderButton.enabled = YES;
    [self.audioRecorder prepareToRecord];
    
    NSString *filename = @"recorder.m4a";
    NSString *docsDir = [self documentsDirectory];
    NSString *destPath = [docsDir stringByAppendingPathComponent:filename];
    DCLog(@"录制文件路径 : %@", destPath);
    
    NSURL *srcURL = self.audioRecorder.url;
    NSURL *destURL = [NSURL fileURLWithPath:destPath];
    NSError *error;
    BOOL success = [[NSFileManager defaultManager] copyItemAtURL:srcURL toURL:destURL error:&error];
    if (success) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"播放录音" style:UIBarButtonItemStylePlain target:self action:@selector(playRecorder)];
    } else {
        //
        DCLog(@"error : %@", error.localizedDescription);
    }
}

- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError *)error
{
    DCLog(@"%@", error);
    self.recorderButton.enabled = YES;
    self.navigationItem.rightBarButtonItem = nil;
}

#pragma mark - AVAudioPlayerDelegate

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    self.recorderButton.enabled = YES;
    self.navigationItem.rightBarButtonItem.enabled = YES;
    DCLog(@"audioPlayerDidFinishPlaying---%d", flag);
}

- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error
{
    self.recorderButton.enabled = YES;
    self.navigationItem.rightBarButtonItem.enabled = YES;
    DCLog(@"audioPlayerDecodeErrorDidOccur---%@", error.localizedDescription);
}

@end
